<template>
  <div class="stock-in-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>入库管理（伍智文）</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card class="search-card">
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="入库单号">
            <el-input
              v-model="searchForm.stockInCode"
              placeholder="请输入入库单号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="入库类型">
            <el-select
              v-model="searchForm.inOutTypeId"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="进货入库" :value="1" />
              <el-option label="销售退货" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="单据状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="草稿" :value="0" />
              <el-option label="待审核" :value="1" />
              <el-option label="已完成" :value="2" />
              <el-option label="驳回" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="仓库">
            <el-select
              v-model="searchForm.warehouseId"
              placeholder="请选择仓库"
              clearable
              filterable
              style="width: 180px"
            >
              <el-option
                v-for="warehouse in warehouseList"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch" :loading="loading">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card class="table-card">
        <template #header>
          <div class="table-header">
            <span>入库单列表</span>
            <div class="table-actions">
              <el-button type="success" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增
              </el-button>
              <el-button type="primary" @click="handleRefresh" :loading="loading">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="tableData"
          stripe
          border
          style="width: 100%"
          :height="tableHeight"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          
          <el-table-column prop="stockInCode" label="入库单号" width="180" show-overflow-tooltip>
            <template #default="{ row }">
              <el-link type="primary">
                {{ row.stockInCode }}
              </el-link>
            </template>
          </el-table-column>
          
          <el-table-column prop="inOutTypeName" label="入库类型" width="120" />
          
          <el-table-column prop="status" label="单据状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="stockInDate" label="入库日期" width="120" />
          
          <el-table-column prop="warehouseName" label="仓库" width="150" />
          
          <el-table-column prop="relatedOrderCode" label="关联单号" width="180" />
          
          <el-table-column prop="supplierName" label="供应商" width="150" show-overflow-tooltip />
          
          <el-table-column prop="contactPerson" label="联系人" width="100" />
          
          <el-table-column prop="contactPhone" label="联系方式" width="120" />
          
          <el-table-column prop="userName" label="经办人" width="100" />
          
          <el-table-column prop="totalQuantity" label="入库数量" width="100" align="right">
            <template #default="{ row }">
              {{ row.totalQuantity || 0 }}
            </template>
          </el-table-column>
          
          <el-table-column label="入库金额" width="120" align="right">
            <template #default="{ row }">
              ¥{{ formatAmount(row.totalAmount) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="createDate" label="制单时间" width="160" />
          
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.pageIndex"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 获取实例
const { proxy } = getCurrentInstance()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const warehouseList = ref([])

// 搜索表单
const searchForm = reactive({
  stockInCode: '',
  inOutTypeId: '',
  status: '',
  warehouseId: ''
})

// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格高度计算
const tableHeight = computed(() => {
  return window.innerHeight - 400
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 草稿
    1: 'warning', // 待审核
    2: 'success', // 已完成
    3: 'danger'   // 驳回
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待审核',
    2: '已完成',
    3: '驳回'
  }
  return statusMap[status] || '未知'
}

// 格式化金额
const formatAmount = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    const response = await proxy.http.post('/api/warehousemodel/GetPageData', {
      pageIndex: 1,
      pageSize: 1000
    }, false)
    
    if (response && (response.status === 0 || response.status === true || response.status === 1)) {
      let data = []
      
      if (response.rows && Array.isArray(response.rows)) {
        data = response.rows
      } else if (response.data?.rows && Array.isArray(response.data.rows)) {
        data = response.data.rows
      } else if (Array.isArray(response.data)) {
        data = response.data
      }
      
      warehouseList.value = data.map(item => ({
        id: item.Id || item.id,
        name: item.WarehouseName || item.warehouseName || item.name
      })).filter(item => item.id && item.name)
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 获取入库单列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      ...searchForm
    }

    // 清理空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    console.log('查询入库单列表，参数:', params)
    
    // 尝试使用GET方法
    const response = await proxy.http.get('/api/WarehousingManagement/GetStockInOrderPageList', params, false)

    console.log('API完整响应:', response)
    console.log('响应数据结构:', JSON.stringify(response, null, 2))

    // 兼容多种响应格式
    if (response) {
      // 检查是否成功（兼容不同的成功标识）
      const isSuccess = response.success === true || 
                       response.status === 0 || 
                       response.status === true || 
                       response.status === 1 ||
                       response.code === 200
      
      if (isSuccess) {
        // 尝试多种数据路径
        let data = []
        let total = 0
        
        if (response.data?.rows && Array.isArray(response.data.rows)) {
          data = response.data.rows
          // 尝试多种可能的total字段名
          total = response.data.total || response.data.recordCount || response.data.dataCount || response.data.totalCount || 0
        } else if (response.rows && Array.isArray(response.rows)) {
          data = response.rows
          // 尝试多种可能的total字段名
          total = response.total || response.recordCount || response.dataCount || response.totalCount || 0
        } else if (Array.isArray(response.data)) {
          data = response.data
          total = response.total || response.recordCount || response.dataCount || response.totalCount || data.length
        } else if (response.data?.data && Array.isArray(response.data.data)) {
          data = response.data.data
          total = response.data.total || response.data.recordCount || response.data.dataCount || response.data.totalCount || 0
        }
        
        tableData.value = data
        pagination.total = total
        
        console.log('表格数据:', tableData.value)
        console.log('总数:', pagination.total)
        console.log('原始响应:', response)
        
        if (data.length === 0) {
          ElMessage.info('暂无数据')
        }
      } else {
        console.error('API返回失败状态:', response)
        ElMessage.error(response?.message || response?.msg || '获取数据失败')
        tableData.value = []
        pagination.total = 0
      }
    } else {
      console.error('API响应为空')
      ElMessage.error('服务器无响应')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('获取入库单数据失败:', error)
    console.error('错误详情:', error.message)
    console.error('错误堆栈:', error.stack)
    
    // 提供更详细的错误信息
    if (error.response) {
      console.error('错误响应:', error.response)
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.statusText}`)
    } else if (error.request) {
      console.error('请求错误:', error.request)
      ElMessage.error('网络请求失败，请检查网络连接或后端服务是否启动')
    } else {
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
    
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.pageIndex = 1
  fetchData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  pagination.pageIndex = 1
  fetchData()
}

// 新增 - 跳转到新增页面
const handleAdd = () => {
  router.push('/wms.stockinorder/stockinorder/add')
}

// 刷新
const handleRefresh = () => {
  fetchData()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  fetchData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.pageIndex = page
  fetchData()
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchWarehouseList()
  fetchData()
})
</script>

<style scoped>
.stock-in-order-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.table-section {
  margin-bottom: 20px;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 搜索表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stock-in-order-container {
    padding: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .table-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
}
</style>
